
import { useEffect } from "react"
import Animated, { cancelAnimation, Easing, StyleProps, useAnimatedStyle, useSharedValue, withDelay, withRepeat, withTiming } from "react-native-reanimated"

export type MovingTextProps = {
    text: string,
    animationThreshold: number,
    style?: StyleProps
}

export const MoveText = ({ text, animationThreshold, style }: MovingTextProps) => {
    const translateX = useSharedValue(0)
    const shouldAnimate = text.length >= animationThreshold
    const textWidth = text.length

    const animateStyle = useAnimatedStyle(() => {
        return {
            transform: [{
                translateX: translateX.value
            }]
        }
    })
    useEffect(() => {
        if (!shouldAnimate) return
        translateX.value = withDelay(1000, withRepeat(withTiming(
            -textWidth, {
            duration: 5000,
            easing: Easing.linear
        }
        ), -1, true))
   
        return () => {
            cancelAnimation(translateX)
            translateX.value = 0;
        }
   
    }, [translateX, shouldAnimate, text, animationThreshold, textWidth])

    return <Animated.Text numberOfLines={1} style={[style,
        animateStyle, shouldAnimate && {
            width: 9999, // 阻止省略号出现
            paddingLeft: 16, // 避免初始字符几乎不可见
        }]

    }>{text}</Animated.Text>
}